package com.rhb.rhbaiagent.App;
import com.rhb.rhbaiagent.advisor.MyLoggerAdvisor;
import com.rhb.rhbaiagent.advisor.ReReadingAdvisor;
import com.rhb.rhbaiagent.chatmemory.FileBaseChatMemory;
import com.rhb.rhbaiagent.chatmemory.MySqlChatMemory;
import com.rhb.rhbaiagent.rag.LoveAppRagCloudAdvisorConfig;
import com.rhb.rhbaiagent.rag.LoveAppRagCustomAdvisorFactory;
//import com.rhb.rhbaiagent.rag.PgVectorStoreConfig;
import com.rhb.rhbaiagent.rag.QueryRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.model.Media;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.MimeTypeUtils;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class LoveApp {
    private final ChatClient chatClient;
    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。\n";

    private final MySqlChatMemory chatMemory;
    /**
     * 初始化AI的客户端
     * @param dashscopeChatModel
     * @param chatMemory
     */
    public LoveApp(ChatModel dashscopeChatModel, MySqlChatMemory chatMemory){
        this.chatMemory = chatMemory;
        String fileDir = System.getProperty("user.dir") + "/tmp/chat-memory";
        // ChatMemory chatMemory = new FileBaseChatMemory(fileDir);
        // 基于内存的对话记忆
//        ChatMemory chatMemory = new InMemoryChatMemory();
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        //自定义的日志拦截器
                        new MyLoggerAdvisor()
                        //自定义推理增强的Advisor
//                        new ReReadingAdvisor()
                )
                .build();
    }

    /**
     * 不基于数据库的会话记忆
     * @param dashscopeChatModel
     */
//    public LoveApp(ChatModel dashscopeChatModel){
//        String fileDir = System.getProperty("user.dir") + "/tmp/chat-memory";
//         ChatMemory chatMemory = new FileBaseChatMemory(fileDir);
//        // 基于内存的对话记忆
////        ChatMemory chatMemory = new InMemoryChatMemory();
//        chatClient = ChatClient.builder(dashscopeChatModel)
//                .defaultSystem(SYSTEM_PROMPT)
//                .defaultAdvisors(
//                        new MessageChatMemoryAdvisor(chatMemory),
//                        //自定义的日志拦截器
//                        new MyLoggerAdvisor()
//                        //自定义推理增强的Advisor
////                        new ReReadingAdvisor()
//                )
//                .build();
//    }

    /**
     * AI基础对话，支持多轮对话记忆
     * @param message
     * @param chatId
     * @return
     */
    public String dochat(String message, String chatId){
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    public String dochatwithPicture(String message, String chatId, String path){
        // 在调用chatClient之前，将图片路径设置到ThreadLocal中
        MySqlChatMemory.setCurrentImagePath(path);
        
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(u -> u.text(message)
                        .media(MimeTypeUtils.IMAGE_PNG, new ClassPathResource(path)))
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    record LoveReport(String title, List<String> suggestions){

    }

    /**
     * AI恋爱报告功能
     * @param message
     * @param chatId
     * @return
     */
    public LoveReport dochatWithReport(String message, String chatId){
        LoveReport loveReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成一个恋爱结果， 标题为{用户名}的恋爱报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);

        log.info("loveReport: {}", loveReport);
        return loveReport;
    }


    @Resource
    private VectorStore loveAppVectorStore;

    @Resource
    private Advisor loveAppRagCloudAdvisor;

//    @Resource
//    private VectorStore pgVectorStore;

    @Resource
    private QueryRewriter queryRewriter;

    @Resource
    private ToolCallback[] allTools;

    public String dochatWithRag(String message, String chatId){
        String rewriteMessage = queryRewriter.doQueryRewrite(message);
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(rewriteMessage)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                //开启自己的日志拦截器，便于观察
                .advisors(new MyLoggerAdvisor())
                //应用知识库进行问答
//                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                //基于云知识平台的增强顾问
//                .advisors(loveAppRagCloudAdvisor)
                //使用的是基于PgVectoreStore的数据库存储
//                .advisors(new QuestionAnswerAdvisor(pgVectorStore)
                //使用自定义的查询增强器（文档查询+上下文增强）
                .advisors(LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(
                        loveAppVectorStore, "已婚"
                ))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }


    public String doChatWithTools(String message, String chatId){
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    public String doChatWithMcp(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    public Flux<String> doChatWithToolsByStream(String message, String chatId){
        return chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .stream()
                .content();
    }

    /**
     * AI对话功能，支持PDF上传和解析
     * @param message 用户消息
     * @param chatId 会话ID
     * @param pdfPath PDF文件路径
     * @return AI回复内容
     */
    public String doChatWithPDF(String message, String chatId, String pdfPath) {
        // 构建包含PDF解析指令的消息
        String enhancedMessage = message + "\n\n请使用PDF解析工具解析以下路径的PDF文件并将内容添加到上下文中：" + pdfPath;
        
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(enhancedMessage)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        
        String content = chatResponse.getResult().getOutput().getText();
        log.info("PDF chat content: {}", content);
        return content;
    }

    /**
     * AI对话功能，支持PDF上传和解析（流式返回）
     * @param message 用户消息
     * @param chatId 会话ID
     * @param pdfPath PDF文件路径
     * @return AI回复内容流
     */
    public Flux<String> doChatWithPDFByStream(String message, String chatId, String pdfPath) {
        // 构建包含PDF解析指令的消息
        String enhancedMessage = message + "\n\n请使用PDF解析工具解析以下路径的PDF文件并将内容添加到上下文中：" + pdfPath;
        
        return chatClient
                .prompt()
                .user(enhancedMessage)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .stream()
                .content();
    }

}
